package com.zjhcsoft.shop.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.zjhcsoft.common.action.SysAbstractAction;
import com.zjhcsoft.shop.model.User;
import com.zjhcsoft.shop.service.UserService;
import com.zjhcsoft.shop.sys.constant.Constants;
import com.zjhcsoft.shop.sys.shoputil.UserUtil;
import com.zjhcsoft.util.Base64;
import com.zjhcsoft.util.Md5Util;

@Controller
public class LoginAction extends SysAbstractAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -807071875998637621L;
	@Resource
	private UserService userService;
	private String loginName;
	private String password;
	private String message;
	private User user;
	
	
	public String login(){
		user=UserUtil.getUserFromCookies();
		return "login";
	}
	
	public String dologin(){
		List<User> list = userService.getUserByLoginName(loginName);
		if(list.size()>0){
			if(list.get(0).getPassword().equals(password)){
				//保存登录信息到cookie
				// MD5加密用户详细信息
				String cookieValueWithMd5 = Md5Util.getMd5(loginName+ password);
				// 将要被保存的完整的Cookie值
				String cookieValue = loginName + Constants.WORD_SEPARATOR+cookieValueWithMd5;
				// 再一次对Cookie的值进行BASE64编码
				String cookieValueBase64 = new String(Base64.encode(cookieValue.getBytes()));
				// 开始保存Cookie
				Cookie cookie = new Cookie(Constants.USER_KEY, cookieValueBase64);
				cookie.setMaxAge(-1);
				cookie.setPath("/");
				ServletActionContext.getResponse().addCookie(cookie);
				return "success";
			}else{
				message="密码错误,请重新输入！";
				return "login";
			}
		}else{
			message="该用户名不存在！";
			return "login";
		}
		
	}
	//退出登录
	public String loginout(){
		Cookie cookie = new Cookie(Constants.USER_KEY,"");
		cookie.setMaxAge(0);
		cookie.setPath("/");
		ServletActionContext.getResponse().addCookie(cookie);
		user=null;
		return "success";
	}
	
	public String getLoginName() {
		return loginName;
	}
	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	
	
}
